<?php
include getcwd().'/includes/settings.php'; 
include_once(getcwd().'/includes/functions.php');
?>
<?php error_reporting (E_ALL ^ E_NOTICE); ?>
<?php
function exception_handler($exception) {
	ob_start();
	print_r($GLOBALS);
	print_r($exception);
	  file_put_contents('exceptions.txt', ob_get_clean(). "\n",FILE_APPEND);
}
set_exception_handler('exception_handler');
?>

<?php
if($_POST['view'] == "settings") { //update user prefs
	include getcwd().'/includes/connection.php';
	$shuf = $_POST['shuffle'];
	$repeat = $_POST['repeat1'];
	$timestamp = $_POST['timestamp'];
	$username = $_POST['user'];
	$result = mysql_query("UPDATE users SET shuffle = $shuf,timestamp = $timestamp,reap = $repeat WHERE username = '$username'") or die(mysql_error());
} 

else if ($_POST['view'] == "addtoplaylist") { //create playlists
$songid = $_POST['songid'];
$name = $_POST['name'];
$file = JUKE."rest/createPlaylist.view?".CREDS."&name=$name&$songid";
$arr = my_xml2array($file);
print_r($arr);
}
else if ($_POST['view'] == "delplaylist") { //delete a playlist
$playlistid = $_POST['playlistid'];
$file = JUKE."rest/deletePlaylist.view?".CREDS."&id=$playlistid";
$arr = my_xml2array($file);
echo "Playlist removed";
}
else if ($_GET['view'] == "mode") {  //gets directories, whether it's music or video
	include_once(getcwd().'/includes/connection.php');
	include_once(getcwd().'/includes/functions.php');
	$type = trim(mysql_prep($_GET['type']));
	$query = "SELECT * from config WHERE '$type' = true";
	$result = mysql_query("SELECT * from config WHERE $type = 'true'") or die('Configure your folders in setup'.mysql_error());
echo "<ul>";
	while($row = mysql_fetch_array($result)){ 
		$id = $row[0]['id'];
		$arr = my_xml2array(JUKE."rest/getIndexes.view?".CREDS."&musicFolderId=$id");
		$o=0;
		while ($o<count($arr[0][0])-2) {
			$i=0;
			while ($i<count($arr[0][0][$o])-2)
				{
					$id=$arr[0][0][$o][$i]['attributes']['id'];
					$name = $arr[0][0][$o][$i]['attributes']['name'];
					echo "<li><div level='0' class='album ui-state-default'><a title='Add Folder to Playlist' class='addfolder' ><img border='0' src='img/addfolderb.gif'></a><a class='clk' album=\"$name\" albumid='$id' href='#'>".$name."</a></div><div class='actrack'></div></li>";
					$i++;
				}
			$o++;
		}
		
	}
	echo "</ul>";
	unset($arr);
}
else if($_GET['view'] == "search") { //searching
	$keyword = urlencode(trim($_GET['keyword']));
	$scope = $_GET['scope'];
	$offset = $_GET['offset'];
	$file = JUKE."rest/search.view?".CREDS."&$scope=$keyword&count=10&offset=$offset";
	$arr = my_xml2array($file);
	$i=0;
	while($i < count($arr[0][0])-2){
		$seconds = $arr[0][0][$i]['attributes']['duration'];
		$mins = floor($seconds/60);
		$secs = $seconds%60;
		if ($secs<6) $secs=$secs.'0';
		elseif ($secs>5 && $secs<10) $secs='0'.$secs;
		$track = $arr[0][0][$i]['attributes']['track'];
		if ($track < 10) $track=' '.chr(32).$track;
		$id = $arr[0][0][$i]['attributes']['id'];
		$album = str_replace("'","''",$arr[0][0][$i]['attributes']['album']);
		$artist = $arr[0][0][$i]['attributes']['artist'];
		$title = $arr[0][0][$i]['attributes']['title'];
		$cover = $arr[0][0][$i]['attributes']['coverArt'];
		echo "<div class='album_track'><div class='trackname'><a title='Add To Playlist' track='$title' class='padd search' time='$mins:$secs' cover='$cover' album='$album' duration='$seconds' artist='$artist' songid='$id' href='#'><img src='img/addb.png' alt='Add Track to Jukebox Queue' /></a><a title='Download this track' href='".JUKE."rest/download.view?".CREDS."&id=$id'><img src='img/down.png' alt='Download this track' /></a><a title='Play this track now' class='playnow' href='#'><img src='img/playb.png'></a><div class='track_num'></div><div class='ttext'>$artist - $title</div></div><div class='duration'>".$mins.':'.$secs."</div></div>";
		$i++;
	} 
	$total = $arr[0][0]['attributes']['totalHits'];
	$y=$total/10;
	$y++;
	echo "<div id='pages'>";
	for($x=1; $x<$y; $x++) {
	$z=$x*10-10;
	echo "<button style='margin-top:4px; margin-bottom:4px; display:inline;' class='spage' offset='$z'>$x</button>";
	}
	echo "<span style='margin-top:3px; float:right;'>Total hits: $total</span>";
	echo "</div>";
	unset($arr);

}
else if($_GET['view'] == "loadstream") {  //loading streams
	$file = curl_get_file_contents($_GET['url']);
	$needle =  '/(?<!file\d=)(http:\/\/\w.*)/';
	preg_match_all($needle,$file,$results);

	$i=0;
	$genre = $_GET['genre'];
	while ($i<count($results[0])) {
		$url=$results[0][$i];
		echo "<div class='newtrack stream' title='$genre' url='$url' style='display: block;'><img src=".SERVER.$_GET['pic']."><div class='grip ui-icon ui-icon-grip-dotted-vertical'></div><div class='tholder'><div class='band'>Digitally Imported</div><div class='tracktext'>$genre</div></div><div class='duration'>~</div></div>";
		$i++;
	}
}
else if($_GET['view'] == "imported") {  //parsing di.fm's homepage for streams
	$haystack = curl_get_file_contents('http://www.di.fm');
	$needle = "/(http:\/\/\w.*\.pls)(?=.*96k)|(?<=Now Playing on\s).*(?=<\/b>)/";
	preg_match_all($needle,$haystack,$results);
	$i=0;
	echo "<div id='s1'>";
	while ($i<count($results[0])){
		$title=$results[0][$i+1];
		$pls=$results[0][$i];
		if ($i<36) echo "<div class='streamgenre'><a href='#' title='$title' pls='$pls'>$title</a></div>";
		else if ($i==36) echo "</div><div id='s2'><div class='streamgenre'><a href='#' title='$title' pls='$pls'>$title</a></div>";
		else if ($i>36) echo "<div class='streamgenre'><a href='#' title='$title' pls='$pls'>$title</a></div>";
		$i+=2;
	} 
	echo "</div>";
}
else if ($_GET['view'] == "randomalbum") { //get random albums
	$number = $_GET['no'];
	$file = JUKE."rest/getAlbumList.view?".CREDS."&size=$number&type=random";
	$arr = my_xml2array($file);
	$i=0;
	while($i < count($arr[0][0])-1){
		echo "<div class='ralbum'><img src='".JUKE."rest/getCoverArt.view?".CREDS."&size=50&id=".$arr[0][0][$i]['attributes']['coverArt']."' /><a href='#' aid=".$arr[0][0][$i]['attributes']['id']."' class='loadalbum'><div class='album_title'>".$arr[0][0][$i]['attributes']['title']."</div></a></div>";
		$i++;
	}
	unset($arr);
}
else if($_POST['view'] == "current") { //sets users current song in the db
	include getcwd().'/includes/connection.php';
	$song = $_POST['currentsong'];
	$artist = $_POST['current'];
	$songid = $_POST['songid'];
	$username = $_POST['user'];
	$duration = $_POST['duration'];
	$cover = $_POST['cover'];
	if ($song == 'online') { $result = mysql_query("UPDATE users SET current = '$song',duration = '',cover = '' WHERE username = '$username'") or die(mysql_error()); }
	else { $result = mysql_query("UPDATE users SET current = '$artist',currentsong = '$song',currentid = '$songid',duration = '$duration',cover = '$cover' WHERE username = '$username'") or die(mysql_error()); }
}
else if($_GET['view'] == "live") {  //get other users status
	include getcwd().'/includes/connection.php';
	$result = mysql_query("SELECT * FROM users") or die(mysql_error());
	while($row = mysql_fetch_array($result)){		
		$duration = $row['duration'];
		$seconds = $duration;
		$mins = floor($seconds/60);
		$secs = $seconds%60;
		if ($secs<6) $secs=$secs.'0';
		elseif ($secs>5 && $secs<10) $secs='0'.$secs;
		if ($row['current'] == '') continue;
		if ($row['current'] == 'idle') echo "<div class='livetrack'>".$row['username']." - ".$row['current']."<br />";
		else {
			$id = $row['currentid'];
			$title = $row['currentsong'];
			$artist = $row['current'];
			$cover = $row['cover'];
			
			if( preg_match('/^(http|https|ftp):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}'.'((:[0-9]{1,5})?\/.*)?$/i' ,$id))
			{
			echo "<div class='livetrack'><a title='Add To Playlist' cover='$cover' artist='$artist' track='$title' class='ladd stream' time='~' duration='~' songid='$id' href='#'><img src='img/addb.png' alt='Add Track to Jukebox Queue' /></a><a title='Play this track now' class='playnow' href='#'><img src='img/playb.png'></a>".$row['username']."</b> - <div class='liveartist'>$artist</div> - <div class='livesong'>$title</div><br />";
			}
			else {
			echo "<div class='livetrack'><a title='Add To Playlist' cover='$cover' artist='$artist' track='$title' class='ladd' time='$mins:$secs' duration='$duration' songid='$id' href='#'><img src='img/addb.png' alt='Add Track to Jukebox Queue' /></a><a title='Play this track now' class='playnow' href='#'><img src='img/playb.png'></a>".$row['username']."</b> - <div class='liveartist'>$artist</div> - <div class='livesong'>$title</div><br />";
		}
	} 
}
}
else if($_GET['view'] == "playlists") { //get playlists
	$file = JUKE."rest/getPlaylists.view?".CREDS;
	$arr = my_xml2array($file);
	$i=0;
	while($i < count($arr[0][0])-1){
	$pid = $arr[0][0][$i]['attributes']['id'];
	echo "<div class='playlisttitle'><a href='#' title='Delete Playlist' class='removepl' pid='$pid'><img border='0' src='img/deleteplaylist.gif' /></a><a href='#' pid='$pid' title='Load Playlist' class='loadplaylist'><img border='0' src='img/loadplaylist.gif' />".$arr[0][0][$i]['attributes']['name']."</a></div>";
		$i++;
	}
	unset($arr);
}
else if($_GET['view'] == "loadplaylist") {  //loads a playlist
	$playlistid = $_GET['id'];
	$file = JUKE."rest/getPlaylist.view?".CREDS."&id=$playlistid";
	$arr = my_xml2array($file);
	$i=0;
	while ($i<count($arr[0][0])-2)
	{
		$cover = $arr[0][0][$i]['attributes']['coverArt'];
		$seconds = $arr[0][0][$i]['attributes']['duration'];
		$mins = floor($seconds/60);
		$secs = $seconds%60;
		if ($secs<6) $secs=$secs.'0';
		elseif ($secs>5 && $secs<10) $secs='0'.$secs;
		$track = $arr[0][0][$i]['attributes']['track'];
		$id = $arr[0][0][$i]['attributes']['id'];
		$album = str_replace("'","''",$arr[0][0][$i]['attributes']['album']);
		$title = $arr[0][0][$i]['attributes']['title'];
		echo "<div class='newtrack' style='display: block;' duration='$seconds' time='$mins:$secs' songid='$id'><img src=".JUKE."rest/getCoverArt.view?".CREDS."&size=200&c=wat&id=$cover><div class='grip ui-icon ui-icon-grip-dotted-vertical'></div><div class='tholder'><div class='band'>".$arr[0][0][$i]['attributes']['artist']."</div><div class='tracktext'>".$arr[0][0][$i]['attributes']['title']."</div></div><div class='duration'>$mins:$secs</div></div>";
		$i++;
	}
	unset($arr);
}

else if($_GET['view'] == "album") { //get album tracks/inner albums
	$albumid = $_GET['id'];
	$file = JUKE."rest/getMusicDirectory.view?".CREDS."&id=$albumid";
	$arr = my_xml2array($file);
	$i=0;
	$level = $_GET['level']+1;
	$cover = $arr[0][0][$i]['attributes']['coverArt'];
	echo "<div id='cover'><img src=".JUKE."rest/getCoverArt.view?".CREDS."&size=200&id=$cover /></div>";
	echo "<div class='tracklist'>";
	while ($i<count($arr[0][0])-2)
	{
		if($arr[0][0][$i]['attributes']['isDir']=="true"){
			$id = $arr[0][0][$i]['attributes']['id'];
			$album = str_replace("'","''",$arr[0][0][$i]['attributes']['album']);
			echo "<div level='$level' class='album_track album inneralbum'><a class='addinner' albumid='$id'><img src='img/addfolderb.gif'></a><a inner='$i' album='$album' albumid='$id' href='#'>".$arr[0][0][$i]['attributes']['title']."</a></div><div class='innertracks'></div>";
			$i++;
			
		}
		else {
			
			$seconds = $arr[0][0][$i]['attributes']['duration'];
			$mins = floor($seconds/60);
			$secs = $seconds%60;
			if ($secs<6) $secs=$secs.'0';
			elseif ($secs>5 && $secs<10) $secs='0'.$secs;
			$track = $arr[0][0][$i]['attributes']['track'];
			if ($track < 10) $track=' '.chr(32).$track;
			$id = $arr[0][0][$i]['attributes']['id'];
			$album = str_replace("'","''",$arr[0][0][$i]['attributes']['album']);
			$artist = $arr[0][0][$i]['attributes']['artist'];
			$title = str_replace($artist,'',$arr[0][0][$i]['attributes']['title']);
			
			//			echo "<div class='album_track'><div class='trackname'><a title='Add To Playlist' track='$title' class='padd' time='$mins:$secs' album='$album' duration='$seconds' artist='$artist' songid='$id' href=".JUKE."rest/jukeboxControl.view?".CREDS."&action=add&id=$id><img src='img/addb.png' alt='Add Track to Jukebox Queue' /></a><a title='Download this track' href=".JUKE."rest/download.view?".CREDS."&id=$id><img src='img/down.png' alt='Download this track' /></a><a title='Play this track now' class='playnow' href='#'><img src='img/playb.png'></a><div class='track_num'>".$track."</div><div class='ttext'>".$arr[0][0][$i]['attributes']['title']."</div></div><div class='duration'>".$mins.':'.$secs."</div></div>";
			echo "<div class='album_track'><div class='trackname'><a title=\"Add To Playlist\" track=\"$title\" class=\"padd\" time=\"$mins:$secs\" album=\"$album\" duration=\"$seconds\" artist=\"$artist\" songid=\"$id\" href=\"#\"><img src='img/addb.png' alt='Add Track to Jukebox Queue' /></a><a title='Download this track' href='".JUKE."rest/download.view?".CREDS."&id=$id'><img src='img/down.png' alt='Download this track' /></a><a title='Play this track now' class='playnow' href='#'><img src='img/playb.png'></a><div class='track_num'>".$track."</div><div class='ttext'>$title</div></div><div class='duration'>".$mins.':'.$secs."</div></div>";
			$i++;
		}
	}
	echo "</div>";
	unset($arr);
}
else if($_GET['view'] == "chat") { //get chat
	$file = JUKE."rest/getChatMessages.view?".CREDS;
	$arr = my_xml2array($file);
	$i = 0;
	$w = count($arr[0][0])-1;
	while ($i < count($arr[0][0])-1)
	{
		$message = explode(" ",$arr[0][0][$i]['attributes']['message']);
		
		if($message[0] != '') { 
			print_r($message[0]."<div class='name'>".$message[2]." : </div>");
		} else {
			print_r("<div class='name'>".$message[2]." : </div>");
		}
			
		for( $d = 3; $d < count($message); $d++ ) {
			print_r($message[$d]." ");
		}	
		echo "<br />";
		$i++;
	}
}
else if($_GET['view'] == "chatsend") { //send chat text
	$nick = $_GET['nick'];
	$message = $_GET['message'];
	$o = chr(40);
	$c = chr(41);
	$msg2 = urlencode($o.date('g:i').$c.' '.$nick.' '.$message);
	$file = JUKE."rest/addChatMessage.view?".CREDS."&message=$msg2";
	file_get_contents($file);	
}
else if($_GET['view'] == "prefs") { //load config
	include getcwd().'/includes/connection.php';
	$username = $_GET['username'];
	$result = mysql_query("SELECT * FROM users WHERE username='$username'") or die(mysql_error());
	$row = mysql_fetch_array($result);
	echo $row['shuffle'].',';
	echo $row['reap'].',';
	echo $row['timestamp'];
}
else if($_GET['view'] == "addfolder") { //add entire album(s) to playlist
	$albumid = $_GET['id'];
	$file = JUKE."rest/getMusicDirectory.view?".CREDS."&id=$albumid";
	$arr = my_xml2array($file);
	$i=0;
	$e=0;
	$cover = $arr[0][0][$i]['attributes']['coverArt'];	
	while ($e<count($arr[0][0])-2) {
		if($arr[0][0][$i]['attributes']['isDir']=="true"){
			$i1=0;
			$albumid1 = $arr[0][0][$i]['attributes']['id'];
			$file1 = JUKE."rest/getMusicDirectory.view?".CREDS."&id=$albumid1";
			$arr1 = my_xml2array($file1);
			while ($i1<count($arr1[0][0])-2) {
				$cover = $arr1[0][0][$i1]['attributes']['coverArt'];	
				$seconds = $arr1[0][0][$i1]['attributes']['duration'];
				$mins = floor($seconds/60);
				$secs = $seconds%60;
				if ($secs<6) $secs=$secs.'0';
				elseif ($secs>5 && $secs<10) $secs='0'.$secs;
				$track = $arr1[0][0][$i1]['attributes']['track'];
				if ($track < 10) $track=' '.chr(32).$track;
				$id = $arr1[0][0][$i1]['attributes']['id'];
				$album = str_replace("'","''",$arr1[0][0][$i1]['attributes']['album']);
				$title = addslashes($arr1[0][0][$i1]['attributes']['title']);
				$artist = $arr1[0][0][$i1]['attributes']['artist'];
				echo "<div class='newtrack' duration='$seconds' num='$track' time='$mins:$secs' songid='$id'><img src='".JUKE."rest/getCoverArt.view?".CREDS."&size=200&c=wat&id=$cover' /><div class='grip ui-icon ui-icon-grip-dotted-vertical'></div><div class='tholder'><div class='band'>$artist</div><div class='tracktext'>$title</div></div><div class='duration'>$mins:$secs</div></div>";
				$i1++;
			}
			$i++;
		}
		else {
			while ($i<count($arr[0][0])-2)
			{
				$seconds = $arr[0][0][$i]['attributes']['duration'];
				$mins = floor($seconds/60);
				$secs = $seconds%60;
				if ($secs<6) $secs=$secs.'0';
				elseif ($secs>5 && $secs<10) $secs='0'.$secs;
				$track = $arr[0][0][$i]['attributes']['track'];
				if ($track < 10) $track=' '.chr(32).$track;
				$id = $arr[0][0][$i]['attributes']['id'];
				$album = str_replace("'","''",$arr[0][0][$i]['attributes']['album']);
				$title = $arr[0][0][$i]['attributes']['title'];
				$artist = $arr[0][0][$i]['attributes']['artist'];
				echo "<div class='newtrack' duration='$seconds' num='$track' time='$mins:$secs' songid='$id' name='$title'><img src='".JUKE."rest/getCoverArt.view?".CREDS."&size=200&c=wat&id=$cover' /><div class='grip ui-icon ui-icon-grip-dotted-vertical'></div><div class='tholder'><div class='band'>$artist</div><div class='tracktext'>$title</div></div><div class='duration'>$mins:$secs</div></div>";
				$i++;
			}
			
		}
		$e++;
	}
	unset($arr);
}
function curl_get_file_contents($URL)
{	
	$c = curl_init();
	$useragent='Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.4) Gecko/20100611 Firefox/3.6.4';
	curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($c, CURLOPT_URL, $URL);
	curl_setopt($c, CURLOPT_USERAGENT, $useragent); 
	$contents = curl_exec($c);
	curl_close($c);

	if ($contents) return $contents;
	else return FALSE;
}

?>
